package com.producteev4j.transport;

import com.producteev4j.exceptions.ProducteevServiceException;
import com.producteev4j.marshall.JacksonMappingUtil;
import com.producteev4j.model.request.ProducteevParam;
import com.producteev4j.model.request.ProducteevParamUtil;
import com.producteev4j.model.request.ProducteevRequest;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: jcarrey
 * Date: 4/07/11
 * Time: 17:07
 * To change this template use File | Settings | File Templates.
 */
public class SimpleTransportImpl extends AbstractTransport {

    // private static final Logger logger = Logger.getLogger(SimpleTransportImpl.class);


    @Override
    protected Object _doGet(ProducteevRequest request) throws ProducteevServiceException {
        try {
            return JacksonMappingUtil.read(getConnection(getFullUrl(request), request.getParams().getParams()).getInputStream(), request.getResponseClass());
        } catch (IOException e) {
            throw new ProducteevServiceException("IOException: " + e, e);
        }
    }

    private URLConnection getConnection(String url, Map<String, ProducteevParam> params) throws ProducteevServiceException {
        try {
            URL expanded = new URL(getURL(url, params));
            return expanded.openConnection();
        } catch (IOException e) {
            // logger.warn("I/O Exception:" + e.getMessage(), e);
            throw new ProducteevServiceException("Error fetching:" + url, e);
        } catch (Exception e) {
            // logger.error("getForObject error:" + e);
            throw new ProducteevServiceException(e.getMessage(), e);
        }
    }

    private String getURL(String url, Map<String, ProducteevParam> params) {
        String aux = new StringBuilder(url).toString();

        for (Map.Entry<String, ProducteevParam> e : params.entrySet()) {
            aux = aux.replace("{" + e.getKey() + "}", ProducteevParamUtil.encode(e.getValue().toString()));
        }
        // logger.debug("Fetching:" + aux);
        return aux;
    }
}
